<template>

  <view class="app-container">
    <text>{{nav}}</text>
    <view class="top-content" style>
    <video ref="localVideo"   crossOrigin="anonymous"  autoplay style="width:200px;height:400px;" muted="muted"></video>
    </view>
    <button @click="gua">挂断</button>
  </view>
</template>

<script>
export default {

  watch: {
    value: {
      // 可以监听对象的单个属性
      handler(newval, oldval) {
        this.getList();
      },
      deep: true
    }
  },
  data() {
    return {
      nav: "",
      sipsession:{},
      userAgent: null,
      adminInfo: {},
      adminData: {},
      groupNemberList: [],
      pkey: null,
      show: false,
      socketOpen: false,
      socketMsgQueue: [],
      src: "../../static/images/nodata.png",
      status: "nomore",
      iconType: "flower",
      loadText: {
        loadmore: "暂无数据",
        loading: "努力加载中",
        nomore: "没有更多数据",
        data: "暂无数据"
      },
      datashow: false,
      value: "",
      tabs: [
        {
          name: 123
        }
      ],
      firstNone: true,
      secondNone: true,
      thirdNone: true,
      // 因为内部的滑动机制限制，请将tabs组件和swiper组件的current用不同变量赋值
      current: 0, // tabs组件的current值，表示当前活动的tab选项
      swiperCurrent: 0, // swiper组件的current值，表示当前那个swiper-item是活动的
      dataList1: [],
      startdata: 0,
      enddata: 0,
      date: "",
      startTime: ""
    };
  },
  computed: {
    // ...mapGetters(['admin_info','admin_data'])
  },
  watch: {
    "$store.state.admin_info"(val) {
      this.adminInfo = val;
      this.UA();
    },
    "$store.state.admin_data"(val) {
      this.adminData = val;
      // console.log(val)
      this.call();
    }
  },
  onReachBottom() {},
  onPullDownRefresh() {
    setTimeout(function() {
      uni.stopPullDownRefresh();
    }, 1000);
  },
  onShow: function() {},
  onLoad: function(val) {
    console.log(this.$store);
    let _this = this;
    //获取pkey
    uni.request({
      url: "/api/index.php?ctl=tool&act=get_pkey", //仅为示例，并非真实接口地址。
      data: {
        user_name: "shyq",
        pwd: "123456"
      },
      header: {
        "content-type": "application/json" //自定义请求头信息
      },
      method: "POST",
      success: res => {
        console.log('获取pkey成功'+res.data.msg)
        // console.log(res.data.msg)
        this.pkey = res.data.data;
        // console.log(this.pkey);
        this.text = "request success";
        _this.pkeyget();
      }
    });
  },
  methods: {
    // 获取token
    pkeyget() {
      uni.request({
        url: "/api/index.php?ctl=tool&act=get_token", //仅为示例，并非真实接口地址。
        data: {
          user_name: "shyq",
          pkey: this.pkey
        },
        header: {
          "content-type": "application/json" //自定义请求头信息
        },
        method: "POST",
        success: res => {
          console.log('获取token成功'+res.data.status);
          // console.log(res.data.status);
          this.session_id = res.data.session_id;
          let data = {
            act: "ma_login",
            access_token: res.data.session_id,
            user_name: "shyq"
          };
          this.$store.dispatch("WEBSOCKET_SEND", JSON.stringify(data));
        }
      });
    },
    // 配置参数注册UA，配置参数所需数据通过长连接登录获取，如上一步返回结果示例
    UA() {
      let _this = this;
      // console.log(_this.adminInfo.admin_info.sip_info.sip_id);
      var user = _this.adminInfo.admin_info.sip_info.sip_id;
      var host = _this.adminInfo.admin_info.sip_info.sip_host;
      var wss = _this.adminInfo.admin_info.sip_info.wss_url;
      let Config = {
        uri: user + "@" + host,
        transportOptions: {
          wsServers: [wss]
        },
        authorizationUser: _this.adminInfo.admin_info.sip_info.sip_id,
        password: _this.adminInfo.admin_info.sip_info.sip_pwd,
        sessionDescriptionHandlerFactoryOptions: {
          peerConnectionOptions: {
            rtcConfiguration: {
              iceServers: [
                { urls: "stun:47.106.114.236:40998" },
                {
                  urls: "turn:47.106.114.236:40998",
                  username: _this.adminInfo.admin_info.sip_info.turn_user,
                  credential: _this.adminInfo.admin_info.sip_info.turn_pwd
                }
              ]
            }
          }
        }
      };
      _this.userAgent = new SIP.UA(Config);
      // 监听成功
      _this.userAgent.on("registered", () => {
        console.log("registered ok", "监听成功");
        // 获取组信息
        uni.request({
          url: "/api/index.php?ctl=group&act=get_group_list", //仅为示例，并非真实接口地址。
          data: {
            admin_id: _this.adminInfo.admin_info.admin_id
          },
          header: {
            "content-type": "application/json" //自定义请求头信息
          },
          method: "POST",
          success: res => {
            // this.pkey = res.data.data;
            // console.log(res);
            this.text = "request success";
            // 获取不同分组下的帽子信息，包含sip_id（返回结果中）：
            uni.request({
              url: "/api/index.php?ctl=group&act=get_group_member_list",
              data: {
                admin_id: _this.adminInfo.admin_info.admin_id,
                g_id: res.data.data[0].g_id
              },
              header: {
                "content-type": "application/json"
              },
              method: "POST",
              success: res => {
                // console.log(res.data.data[0],'sshhhhhhhhhhhhhhhhhhhhhhhhhhhh');
                this.groupNemberList = res.data.data;
                this.text = "request success";
                _this.monitorList(res.data.data[0].user_id);
              }
            });
            // _this.pkeyget();
          }
        });
      });
      // 监听失败
      _this.userAgent.on("registrationFailed", (response, cause) => {
        // console.log("registrationFailed, ", response, cause);
      });
    },
    // 与帽子建立连接
    monitorList(id) {
      let data = { act: "ma_set_sip_info", v_type: "1", user_id: id };
      this.$store.dispatch("WEBSOCKET_SEND", JSON.stringify(data));
      // console.log(data);
    },
    // 帽子成功接收通话请求并成功响应后开始发起通话
    call() {
      // console.log(
      //   "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
      // );
      let _this = this;

      // 配置通话参数
      const user = _this.groupNemberList[0].sip_id;
      const host = _this.adminInfo.admin_info.sip_info.sip_host;
      const uri = user + "@" + host;
      const options = {
        sessionDescriptionHandlerOptions: {
          constraints: {
            audio: true,
            video: true //或直接写“video:true”，若选择语音通话则为“video:false”
          }
        }
      };
      // 拨打电话
      // console.log(
      //   uri,
      //   options,
      //   "wfeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
      // );
      let outgoingSession = _this.userAgent.invite(uri, options); //“1100200@47.112.134.21:5060”为被拨打者账号
      _this.sipsession=outgoingSession
      // console.log(
      //   outgoingSession,
      //   "mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm"
      // );
      // 设置拨打结果监听
      outgoingSession.on("accepted", data => {
        var remoteVideo = this.$refs.remoteVideo;
        // var localVideo=this.$refs.localVideo
        var localVideo = document.querySelector("#localVideo video");
        // var localVideo = document.getElementById("localVideo");
        console.info("onAccepted - ", data); // We need to check the peer connection to determine which track was added
        // console.log("wfefffffffffffffffffffffffffffff");

        var pc = outgoingSession.sessionDescriptionHandler.peerConnection;

        // Gets remote tracks
        var remoteStream = new MediaStream();
        // console.log(remoteStream, "remote");
        pc.getReceivers().forEach(function(receiver) {
          remoteStream.addTrack(receiver.track);
          window.rs = remoteStream;
          // console.log(receiver, "reciver");
          // console.log(
          //   "----------------------------------------------------------------------------"
          // );
          _this.nav = navigator.userAgent;
          // console.log(_this.nav);
          // console.log(
          //   "----------------------------------------------------------------------------"
          // );
          document.getElementsByTagName("video")[0].srcObject = rs;
        });
      });
      outgoingSession.on("rejected", (response, cause) => {
        console.log("onRejected - ", response, cause);
      });

      outgoingSession.on("failed", (response, cause) => {
        console.log("onFailed - ", response, cause);
      });

      outgoingSession.on("terminated", (message, cause) => {
        console.log("onTerminated - ", message, cause);
      });
    },
    gua(){
      // console.log(111111111111)
      this.sipsession.terminate()
    }
  }
};
</script>

<style lang="scss" scoped>
.app-container {
  position: relative;
  height: 100%;
  .top-content {
    height: 160upx;
    background: linear-gradient(to left, #1040be, #026dff);
  }
  .box-contet {
    height: calc(100% - 180upx);
    margin-top: 20rpx;
    .cardlist {
      height: 100%;
      .swiper-item {
        height: 100%;
      }
    }
  }
}
.date {
  margin-right: 10rpx;
  display: flex;
  align-items: center;

  image {
    width: 50rpx;
    height: 50rpx;
  }
}
.top {
  z-index: 10;
  position: absolute;
  padding: 30rpx 30rpx 18rpx 30rpx;
  width: 100%;
  top: 50rpx;
  background-color: white;
  display: flex;
  border-radius: 40rpx 40rpx 0 0;

  .btn {
    position: absolute;
    right: 35rpx;
    border-radius: 16rpx;
  }
  /deep/ .u-btn--primary {
    background: linear-gradient(to left, #1040be, #026dff);
  }
  /deep/ .uni-input-placeholder {
    font-size: 22rpx;
    color: #989898 !important;
    // line-height:100upx;
  }
  /deep/ .u-mode-plain-primary {
    border: 1px solid #eee;
    box-shadow: 0 0 20rpx #eee;
    border-radius: 16rpx;
    color: #989898;
  }
  /deep/ .u-flex {
    margin-right: 80rpx;
  }
  .image {
    position: absolute;
    width: 28rpx;
    height: 34rpx;
    left: 45rpx;
    // height: 80upx;
  }
  /deep/ .u-size-default {
    padding: 18rpx 24rpx 18rpx 50rpx;
  }
  /deep/ .u-input--border {
    border: 1px solid #eee !important;
    box-shadow: 0 0 20rpx #eee;
    border-radius: 16rpx;
    // color: #989898 !important;
    // height: 60upx;
    // line-height: 20upx;
  }
  /deep/ .u-input__input {
    min-height: 55upx !important;
    color: #989898 !important;
  }
}

.cardlist {
  background: #ffffff;
}
.scrollHeight {
  height: 100%;
}
.card {
  width: 100%;
  padding: 0rpx 30rpx 30rpx 30rpx;
}
/deep/ .u-drawer-content {
  height: 90% !important;
}
/deep/ .u-calendar__bottom__choose {
  height: 0rpx !important;
}
</style>
